package controller;

import model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class userController {

    @Resource
    private UserService userService;

    @RequestMapping("/hello")
    public String hello(HttpServletRequest request, Model model){
        int id = Integer.parseInt(request.getParameter("id"));
        User u = userService.selectById(id);
        model.addAttribute("user",u);
        return "hello";
    }
    @RequestMapping(value="/login",method = RequestMethod.GET)
    public String login(HttpServletRequest request,Model model){

        return "login";
    }

    @RequestMapping(value="/login" , method = RequestMethod.POST)
    public String toLogin(User u,Model model){
        UsernamePasswordToken token = new UsernamePasswordToken();
        try {
            token.setUsername(u.getUserName());
            token.setPassword(u.getPassword().toCharArray());
            SecurityUtils.getSubject().login(token);
        }catch (UnknownAccountException ue){
            model.addAttribute("msg","用户名密码不对");
            ue.printStackTrace();
            return "login";
        }
        model.addAttribute("user",u);
        return "index";
    }
}
